package reflect;

import java.lang.reflect.Field;

/**
 * 反射机制获取属性；
 */
public class Demo09Reflect {
    public static void main(String[] args) throws Exception {
        //1.普通方式；
        Teacher teacher = new Teacher();
        teacher.name = "王伟超";//很少用，一般teacher.setName（“王伟超”）；
        System.out.println(teacher.name);//很少用，一般teacher.getname();

        //2.反射方式；
        Class cls = Class.forName("reflect.Teacher");
        Object obj = cls.newInstance();
        Field field = cls.getField("name");
        field.set(obj, "赵丽颖");
        System.out.println(field.get(obj));

        //3.练习：反射方式设置age的属性值为39岁
        Field field1 = cls.getDeclaredField("age");
        field1.setAccessible(true);//打开私有成员的访问权限；
        field1.set(obj, 39);
        System.out.println(field1.get(obj));
        field1.setAccessible(false);//关闭私有成员的访问权限；
    }
}
